package com.ryx.service.Impl;

import com.ryx.entity.SysUserRole;
import com.ryx.exception.GlobalException;
import com.ryx.exception.code.BaseResponseCode;
import com.ryx.mapper.SysUserRoleMapper;
import com.ryx.service.UserRoleService;
import com.ryx.vo.req.UserOwnRoleReqVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @BelongsPackage: com.ryx.service.Impl
 * @Author: 容永轩
 * @CreateTime: 2021-01-04
 * @Description:
 */
@Service
@Transactional
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;


    @Override
    public List<String> getRoleIdsByUserId(String userId) {

        return sysUserRoleMapper.getRoleIdByUserId(userId);
    }

    //中间表的操作，我们到时在具体的业务调用在进行调用，其实可以直接注入然后使用，
    // 但是当业务越多就会越麻烦，中间表的操作一般最好单独出来
    @Override
    public void addUserRoleInfo(UserOwnRoleReqVo vo) {
        //首先删除他们的关联数据
        sysUserRoleMapper.removeRoleByUserId(vo.getUserId());

        if (vo.getRoleIds() == null || vo.getRoleIds().isEmpty()){
            return;
        }

        List<SysUserRole> list =new ArrayList<>();

        //vo是我们表单的数据
        //遍历我们的id集合，通过这个id和传入的vo把关联表的数据填充好
        for (String roleId : vo.getRoleIds()) {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setCreateTime(new Date());
            sysUserRole.setUserId(vo.getUserId());
            sysUserRole.setRoleId(roleId);
            sysUserRole.setId(UUID.randomUUID().toString());
            list.add(sysUserRole);

        }

        int i = sysUserRoleMapper.batchInsertUserRole(list);
        if (i < 0){
            throw new GlobalException(BaseResponseCode.OPERATION_ERROR);
        }

    }

    @Override
    public List<String> getUserIdsByRoleIds(List<String> roleIds) {

        return sysUserRoleMapper.getUserIdsByRoleIds(roleIds);
    }

    @Override
    public List<String> getUserIdsByRoleId(String roleId) {
        return sysUserRoleMapper.getUserIdsByRoleId(roleId);
    }

    @Override
    public int removeUserRoleId(String roleId) {

        return sysUserRoleMapper.removeUserRoleId(roleId);
    }
}
